activity:ide
public class MainActivity extends Activity
{
private Button startButton = null;
private Button stopButton = null;
private Intent intent = null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get instance
startButton = (Button) findViewById(R.id.startButton);
stopButton = (Button) findViewById(R.id.stopButton);
intent = new Intent(MainActivity.this, MyService.class);
//set start service button click listener
startButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View view)
{
startService(intent);
}
});
//set stop service button click listener
stopButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View view)
{
stopService(intent);
}
});
}
}this
receiver:get
public class BootBroadcastReceiver extends BroadcastReceiver{it
@Override
public void onReceive(Context context, Intent intent)
{
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()))
{
Intent startServiceIntent = new Intent(context, MyService.class);
startServiceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(startServiceIntent);
}
}
}io
service(重點):ast
public class MyService extends Service
{
AlarmManager mAlarmManager = null;
PendingIntent mPendingIntent = null;
@Override
public void onCreate()
{
//start the service through alarm repeatly
Intent intent = new Intent(getApplicationContext(), MyService.class);
mAlarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
mPendingIntent = PendingIntent.getService(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
long now = System.currentTimeMillis();
mAlarmManager.setInexactRepeating(AlarmManager.RTC, now, 60000, mPendingIntent);
super.onCreate();
}class
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Toast.makeText(getApplicationContext(), "Callback Successed!", Toast.LENGTH_LONG).show();
return START_STICKY;
}cli
@Override
public IBinder onBind(Intent intent)
{
return null;
}sed
@Override
public void onDestroy()
{
super.onDestroy();
}
}List