2012-04-27 5 views
0

私のアプリケーションでは、startActivityメソッドを使用して別のアクティビティ(外部アクティビティ)を起動します。 startActivityメソッドの代わりにstartActivityForResultメソッドを使用できるので、この2番目のアプリケーションの起動時に通知を受けたいと思います。そのような通知を受け取る他の仕組みがありますか?アプリケーションが開始されたという通知を受け取るにはどうすればよいですか?

答えて

1

これを試すと、最初のアクティビティで2番目のアクティビティでstartServiceを呼び出します。

startService(新しいインテント(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; 
} 

}

関連する問題