2012-04-27 31 views
0

在我的應用程序中,我使用startActivity方法啓動另一項活動(外部活動)。 我想在第二個應用程序啓動時收到通知,所以我可以使用startActivityForResult方法而不是startActivity方法。是否有其他機制可以收到此類通知?如何接收應用程序已啓動的通知?

回答

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; 
} 

}

相關問題