如何收到应用程序已启动的通知?

时间:2012-04-27 09:08:18

标签: android android-activity

在我的应用程序中,我使用startActivity方法启动另一个活动(外部活动)。 我希望在第二个应用程序启动时收到通知,因此我可以使用startActivityForResult方法而不是startActivity方法。是否有其他机制来接收此类通知?

1 个答案:

答案 0 :(得分:1)

你可以试试这个,在你第二个活动的第一个活动中调用startService。

startService(new Intent(this,NotificationService.class));

创建包含以下内容的NotificationService.java:

package com.sample;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

 import android.app.Notification;
   import android.app.NotificationManager;
   import android.app.PendingIntent;
   import android.app.Service;
   import android.content.Context;
  import android.content.Intent;

  import android.os.IBinder;
  import android.preference.PreferenceManager;
  import android.util.Log;
  import android.widget.Toast;
  public class NotificationService extends Service
   {
private final int UPDATE_INTERVAL = 10 * 1000;
private Timer timer = new Timer();  
private static final int NOTIFICATION_EX = 1;
private static final String TAG = "NotificationService";
private NotificationManager notificationManager;
ArrayList<HashMap<String, String>> currentForecast = new ArrayList<HashMap<String, String>>();

CharSequence tickerText="notifi";
public NotificationService(){}

public IBinder onBind1(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}


@Override   
public void onCreate() {
  //code to execute when the service is first created

}   

@Override   
public void onDestroy() {   

    if (timer != null){
        timer.cancel();
    } 
}

@Override

public  int onStartCommand(final Intent intent, final int flags, final int startid) {  

    notificationManager = (NotificationManager) 
    getSystemService(Context.NOTIFICATION_SERVICE);


    int icon = R.drawable.iconToDisplayOnNotification;
    long when = System.currentTimeMillis();

    final Notification notification = new Notification(icon, tickerText, when);

    final Context context = getApplicationContext();
    final CharSequence contentTitle = "titleForNotification";
    final CharSequence contentText = "TextForNotification";
    Intent notificationIntent = new Intent(this, ActivityTobeCalledOnNotificationSelect.class);
    final PendingIntent contentIntent = PendingIntent.getActivity(this,0, notificationIntent, 0);

    notification.setLatestEventInfo(context, contentTitle,contentText, contentIntent);

    notificationManager.notify(NOTIFICATION_EX, notification);

    Toast.makeText(this, "Started!", Toast.LENGTH_LONG);
    timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {
            // Check if there are updates here and notify if true
             Log.w(TAG,"run");
        }       

    }
,10, UPDATE_INTERVAL);

    return START_STICKY ;


}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

}

相关问题