从我的应用程序内部停止IntentService?

时间:2014-02-19 17:34:39

标签: android google-cloud-messaging

我正在构建某种聊天程序,它使用GCM通知用户消息可用。我使用WakefulBroadcastReceiverIntentService跟随gcm客户端示例,一切都按预期工作。

BroadcastReceiver

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // Explicitly specify that GcmIntentService will handle the intent.
        ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName());
        // Start the service, keeping the device awake while it is launching.
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
}

IntentService

public class GcmIntentService extends IntentService {
    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;

    public GcmIntentService() {
        super("GcmIntentService");
    }

    public static final String TAG = "IOAN";

    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty()) {  // has effect of unparcelling Bundle
            if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                // Post notification of received message.
                sendNotification(extras.getString("sender"), extras.getString("message"));
                Log.i(TAG, "Received: " + extras.toString());
            }
        }
        // Release the wake lock provided by the WakefulBroadcastReceiver.
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }
   //... more stuff
}

因此IntentService会向我的应用程序发送通知。

现在,当用户关闭我的应用程序时(后退按钮 - >您确定要退出吗? - >是),我还想要一个复选框“你还想要接收消息吗?” (或类似的东西),如果用户选择不接收消息,我想停止处理gcm消息的服务,并在应用程序再次运行时重新启动它。

我该怎么做?

编辑:我尝试了stopService(new Intent(MainActivity.this,GcmIntentService.class));,但我仍然收到通知。

编辑2:似乎boolean中的SharedPreferences值工作得很好......任何更好的解决方案?

0 个答案:

没有答案