簡體   English   中英

如何停止服務意圖並取消待處理的通知

[英]How to stop Service Intent and cancel pending Notification

我已按照http://developer.android.com/training/notify-user/index.html中的教程進行操作

它運作良好。 但是我想要的是:當我單擊ping時,舊服務將停止,然后再次創建該服務。 因此,如果我多次單擊id,它將僅通知我一次。

問題:如果將時間設置為10,則單擊“ Ping”按鈕。 然后5秒鍾后,我再次單擊它。 它會通知我兩次。

我想要的是:如果我將時間設置為10,則單擊“ Ping”按鈕。 然后,在5秒鍾后,我單擊它,它將僅通知一次,最后一次單擊按鈕后10秒鍾。

public class MainActivity extends Activity {

private Intent mServiceIntent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Creates an explicit Intent to start the service that constructs and
    // issues the notification.
    mServiceIntent = new Intent(getApplicationContext(), PingService.class);
}

/*
 * Gets the values the user entered and adds them to the intent that will be
 * used to launch the IntentService that runs the timer and issues the
 * notification.
 */
public void onPingClick(View v) {

        stopCurrentService();
        int seconds;

        // Gets the reminder text the user entered.
        EditText msgText = (EditText) findViewById(R.id.edit_reminder);
        String message = msgText.getText().toString();

        mServiceIntent.putExtra(CommonConstants.EXTRA_MESSAGE, message);
        mServiceIntent.setAction(CommonConstants.ACTION_PING);
        Toast.makeText(this, R.string.timer_start, Toast.LENGTH_SHORT).show();

        // The number of seconds the timer should run.
        EditText editText = (EditText) findViewById(R.id.edit_seconds);
        String input = editText.getText().toString();

        if (input == null || input.trim().equals("")) {
            // If user didn't enter a value, sets to default.
            seconds = R.string.seconds_default;
        } else {
            seconds = Integer.parseInt(input);
        }
        int milliseconds = (seconds * 1000);
        mServiceIntent.putExtra(CommonConstants.EXTRA_TIMER, milliseconds);
        // Launches IntentService "PingService" to set timer.

        startService(mServiceIntent);

}

private void stopCurrentService() {
    ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningServiceInfo> serviceList = activityManager
            .getRunningServices(Integer.MAX_VALUE);

    if (serviceList.size() <= 0) {  }
    int size = serviceList.size();
    for (int i = 0; i < size; i++) {
        RunningServiceInfo serviceInfo = serviceList.get(i);
        ComponentName serviceName = serviceInfo.service;
        if (serviceName.getClassName().equals(PingService.class.getName())) {   
            try {
                Intent intentstop = new Intent();            
                intentstop.setComponent(serviceName);
                getApplicationContext().stopService(intentstop);            
            } catch (SecurityException e) {
                e.printStackTrace();

            }

        }
    }       
 }

}

PingService創建一個包含2個按鈕的通知:一個按鈕暫停通知,另一個按鈕取消通知。

public class PingService extends IntentService {

private NotificationManager mNotificationManager;
private String mMessage;
private int mMillis;
NotificationCompat.Builder builder;
private boolean status;

public PingService() {

    // The super call is required. The background thread that IntentService
    // starts is labeled with the string argument you pass.

    super("com.example.android.pingme");
}

@Override
protected void onHandleIntent(Intent intent) {
    // The reminder message the user set.
    mMessage = intent.getStringExtra(CommonConstants.EXTRA_MESSAGE);
    // The timer duration the user set. The default is 10 seconds.
    mMillis = intent.getIntExtra(CommonConstants.EXTRA_TIMER,
            CommonConstants.DEFAULT_TIMER_DURATION);
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    String action = intent.getAction();
    // This section handles the 3 possible actions:
    // ping, snooze, and dismiss.
    if (action.equals(CommonConstants.ACTION_PING)) {
        issueNotification(intent, mMessage);
    } else if (action.equals(CommonConstants.ACTION_SNOOZE)) {
        nm.cancel(CommonConstants.NOTIFICATION_ID);
        Log.d(CommonConstants.DEBUG_TAG, getString(R.string.snoozing));
        // Sets a snooze-specific "done snoozing" message.
        issueNotification(intent, getString(R.string.done_snoozing));

    } else if (action.equals(CommonConstants.ACTION_DISMISS)) {
        nm.cancel(CommonConstants.NOTIFICATION_ID);
    }
}

private void issueNotification(Intent intent, String msg) {
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // Sets up the Snooze and Dismiss action buttons that will appear in the
    // expanded view of the notification.
    Intent dismissIntent = new Intent(this, PingService.class);
    dismissIntent.setAction(CommonConstants.ACTION_DISMISS);
    PendingIntent piDismiss = PendingIntent.getService(this, 0,
            dismissIntent, 0);

    Intent snoozeIntent = new Intent(this, PingService.class);
    snoozeIntent.setAction(CommonConstants.ACTION_SNOOZE);
    PendingIntent piSnooze = PendingIntent.getService(this, 0,
            snoozeIntent, 0);

    // Constructs the Builder object.
    builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_notification)
            .setTicker("Ping ! ping ! PIng!")
            .setContentTitle(getString(R.string.notification))
            .setContentText(getString(R.string.ping))
            .setDefaults(Notification.DEFAULT_ALL)
            // requires VIBRATE permission
            /*
             * Sets the big view "big text" style and supplies the text (the
             * user's reminder message) that will be displayed in the detail
             * area of the expanded notification. These calls are ignored by
             * the support library for pre-4.1 devices.
             */
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .addAction(R.drawable.ic_stat_dismiss,
                    getString(R.string.dismiss), piDismiss)
            .addAction(R.drawable.ic_stat_snooze,
                    getString(R.string.snooze), piSnooze);

    /*
     * Clicking the notification itself displays ResultActivity, which
     * provides UI for snoozing or dismissing the notification. This is
     * available through either the normal view or big view.
     */
    Intent resultIntent = new Intent(this, ResultActivity.class);
    resultIntent.putExtra(CommonConstants.EXTRA_MESSAGE, msg);
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
            | Intent.FLAG_ACTIVITY_CLEAR_TASK);

    // Because clicking the notification opens a new ("special") activity,
    // there's
    // no need to create an artificial back stack.
    PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,
            resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    builder.setContentIntent(resultPendingIntent);
    startTimer(mMillis);
}

// Starts the timer according to the number of seconds the user specified.
private void startTimer(int millis) {
    Log.d(CommonConstants.DEBUG_TAG, getString(R.string.timer_start));
    try {
        Thread.sleep(millis);

    } catch (InterruptedException e) {
        Log.d(CommonConstants.DEBUG_TAG, getString(R.string.sleep_error));
    }
    Log.d(CommonConstants.DEBUG_TAG, getString(R.string.timer_finished));
    issueNotification(builder);

}

private void issueNotification(NotificationCompat.Builder builder) {
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    // Including the notification ID allows you to update the notification
    // later on.
    mNotificationManager.notify(CommonConstants.NOTIFICATION_ID,
            builder.build());
}

@Override
public void onDestroy() {
    super.onDestroy();
 }

}

我已經叫stopService(),但是舊的通知又出現了。

我想要的是它會在最后一次點擊后10秒鍾通知我一次。

您可以使用處理程序來停止/啟動服務。 請看我的代碼。 它與您的代碼不完全相關,但是您可以理解。 點擊此鏈接

您可以在Runnable的Run方法中進行檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM