我使用的是被称为在活动'A'多次被AlarmManager创建的服务。我的服务是反复检查从服务器响应,当反应是真实的新活动B开始。现在,当活动B开始我想停止服务以及AlarmManager。我怎样才能做到这一点?
我的'A'活动code调用服务是继
日历CAL = Calendar.getInstance(); cal.add(Calendar.SECOND,40); 意向意图=新意图(这一点,response.class); //添加额外的包 intent.putExtra(富,酒吧); //开始服务 // startService(意向); pintent = PendingIntent.getService(在此,0,意图,0); 报警=(AlarmManager)getSystemService(Context.ALARM_SERVICE); INT I; 我= 15; alarm.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), 我* 1000,pintent); startService(意向);我也试图在活动'B'这个code段停止AlarmManager但不能
意图sintent =新意图(这一点,response.class); pintent = PendingIntent.getService(在此,0,sintent,0); 报警=(AlarmManager)getSystemService(Context.ALARM_SERVICE); stopService(sintent); alarm.cancel(pintent);解决方案
在活动B,你应该使用相同的环境中创建sIntent如您在活动A创建它。
因此,在活动A我想补充一点
私有静态上下文的背景下;公共静态上下文getAppContext(){ 返回ActivityA.context;}和里面的onCreate()活动A的方法,初始化上下文
=背景getApplicationContext();而在活动B创建sIntent是这样的:
意向意图=新意图(ActivityA.getAppContext(),ServiceClass.class);intent.putExtra(fsasf,酒吧);的PendingIntent pintent = PendingIntent.getService(这一点,0,意向,0);AlarmManager报警=(AlarmManager)getSystemService(Context.ALARM_SERVICE);stopService(意向);alarm.cancel(pintent);I am using a service which is called in Activity 'A' repeatedly created by AlarmManager. My service is checking repeatedly response from server, when response is true new Activity B is started. Now when activity B is started i want to stop service as well as AlarmManager. how can i do this??
my 'A' activity code for calling service is following
Calendar cal = Calendar.getInstance(); cal.add(Calendar.SECOND, 40); Intent intent = new Intent(this, response.class); // Add extras to the bundle intent.putExtra("foo", "bar"); // Start the service // startService(intent); pintent = PendingIntent.getService(this, 0, intent, 0); alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE); int i; i = 15; alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), i * 1000, pintent); startService(intent);I have also tried this code snippet in Activity 'B' to stop AlarmManager but fail
Intent sintent = new Intent(this, response.class); pintent = PendingIntent.getService(this, 0, sintent, 0); alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE); stopService(sintent); alarm.cancel(pintent);解决方案
In Activity B you should create sIntent with the same context as you created it in Activity A.
So in Activity A I would add this
private static Context context; public static Context getAppContext(){ return ActivityA.context; }and inside onCreate() method of Activity A, initialize context
context=getApplicationContext();And in Activity B create sIntent like this:
Intent intent = new Intent(ActivityA.getAppContext(), ServiceClass.class); intent.putExtra("fsasf", "bar"); PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0); AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE); stopService(intent); alarm.cancel(pintent);
更多推荐
如何的Android在其他活动停止AlarmManager
发布评论