İçeriğe geç

Android Web Servis İçerik Bağlantısı Başlatma ve Sonlandırma

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context="com.example.downloadservice.MainActivity">
	<Button android:text="START" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/btnStartService" />
	<Button android:text="STOP" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/btnStopService" />
</LinearLayout>
public class MyService extends Service {@Override
  public IBinder onBind(Intent arg0) {
    return null;
  }@Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    try {
      int result = DownloadFile(new URL("http://www.berkayakcay.com.tr/1000.pdf"));
      Toast.makeText(getBaseContext(), "Downloaded" + result + "bytes", Toast.LENGTH_LONG).show();
    } catch(MalformedURLException e) {
      e.printStackTrace();
    }
    return START_STICKY;
  }@Override
  public void onDestroy() {
    super.onDestroy();

    Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
  }

  private int DownloadFile(URL url) {
    try {
      Thread.sleep(1000);
    } catch(InterruptedException e) {
      e.printStackTrace();
    }
    return 100;
  }
}
public class MainActivity extends AppCompatActivity {@Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btnStart = (Button) findViewById(R.id.btnStartService);
    btnStart.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        startService(new Intent(getBaseContext(), MyService.class));
      }

    });
    Button btnStop = (Button) findViewById(R.id.btnStopService);
    btnStop.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        stopService(new Intent(getBaseContext(), MyService.class));
      }
    });
  }
}
web-service
Kategori:Android

İlk Yorumu Siz Yapın

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir