layout
service
activity
manifest
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/btnStartService" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="startService" android:text="Start Service" /> <Button android:id="@+id/btnStopService" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="stopService" android:text="Stop Service" /> </LinearLayout>
service
package com.example.adehodijah.myservice; /** * Created by AdeHodijah on 2/27/2018. */ import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.IBinder; import android.widget.Toast; import com.google.android.gms.common.api.GoogleApiClient; public class TheService extends Service { MediaPlayer mp; GoogleApiClient mGoogleApiClient; @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, "The Service Started", Toast.LENGTH_LONG).show(); mp = MediaPlayer.create(this, R.raw.canon); mp.start(); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); mp.stop(); Toast.makeText(this, "The Service Destroyed", Toast.LENGTH_LONG).show(); } }
activity
package com.example.adehodijah.myservice; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void startService(View view) { startService(new Intent(getBaseContext(), TheService.class)); } public void stopService(View view) { stopService(new Intent(getBaseContext(), TheService.class)); } }
manifest
<service android:name=".TheService" />
Komentar
Posting Komentar