如何停止由警报管理器定期触发的服务

时间:2015-02-19 14:39:05

标签: android service alarmmanager

我正在尝试使用服务来运行后台任务的一些教程。我还尝试了服务如何定期触发操作。但是,当我触发定期服务时,即使使用stopService(intent)命令后也无法阻止它。尝试了各种代码,但服务仍然不会停止,停止它的唯一方法是卸载应用程序。
我采用了使用BroadcastReceiverService和我也使用了AlarmManager
MainActivity.java:
 public class MainActivity extends Activity implements View.OnClickListener {

TextView tvResults;
Button startService, stopService;
Calendar cal;
Intent intent;
PendingIntent pintent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    startService = (Button) findViewById(R.id.btnStartService);
    stopService = (Button) findViewById(R.id.btnStopService);
    tvResults = (TextView) findViewById(R.id.tvResults);

    startService.setOnClickListener(this);
    stopService.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    AlarmManager alarm;
    switch (v.getId()) {

    case R.id.btnStartService:

        Calendar cal = Calendar.getInstance();

        Intent intent = new Intent(this, MyService.class);
        PendingIntent pintent = PendingIntent
                .getService(this, 0, intent, 0);

        alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        // schedule for every 10 seconds
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                10 * 1000, pintent);

        // //other way to do it,not periodically
        // Context context = getApplicationContext();
        // // use this to start and trigger a service
        // Intent i = new Intent(context, MyService.class);
        // // potentially add data to the intent
        // i.putExtra("Service_Key", "Getting email periodically");
        // context.startService(i);
        // //end of non periodic

        tvResults.setText("Success");

        break;

    case R.id.btnStopService:

        PendingIntent pendingIntent = PendingIntent
                .getBroadcast(MainActivity.this, 1, new Intent(
                        MainActivity.this, MyService.class),
                        PendingIntent.FLAG_UPDATE_CURRENT);
        alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarm.cancel(pendingIntent);

        // Intent i = new Intent(this, MyService.class);
        // if (stopService(i)) {
        // tvResults.setText("Stopped service");
        // }
        break;
    }
}
}


MyService.java:
    `public class MyService扩展Service {

@Override
public IBinder onBind(Intent intent) {

    return null;
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    String primaryEmail = getEmail(getApplicationContext());

    Toast.makeText(getApplicationContext(), "primary email: " +primaryEmail, Toast.LENGTH_SHORT).show();

    return Service.START_NOT_STICKY;
}


//get primary email
 static String getEmail(Context context) {
        AccountManager accountManager = AccountManager.get(context); 
        Account account = getAccount(accountManager);

        if (account == null) {
          return null;
        } else {
          return account.name;
        }
      }

 //get google email
      private static Account getAccount(AccountManager accountManager) {
        Account[] accounts = accountManager.getAccountsByType("com.google");
        Account account;
        if (accounts.length > 0) {
          account = accounts[0];      
        } else {
          account = null;
        }
        return account;
      }
  }


MyReceiver.java:
公共类MyReceiver扩展了BroadcastReceiver {

private static final long REPEAT_TIME=1000*10;

@Override
public void onReceive(Context context, Intent intent) {

AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context,MyService.class);
PendingIntent pending= PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);

Calendar cal = Calendar.getInstance();

//start 30 seconds after boot has completed
cal.add(Calendar.SECOND, 30);

//fetch after every 10seconds
service.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), REPEAT_TIME, pending);

}
}

1 个答案:

答案 0 :(得分:0)

在AlarmManager上有一个取消方法。构建用于启动它的相同意图,然后将其传递给cancel方法。

http://developer.android.com/reference/android/app/AlarmManager.html#cancel%28android.app.PendingIntent%29