我有服务

public class GcmIntentService extends IntentService{...}


管理通知。
如果用户不在应用程序中,则在收到通知时,轻按通知可恢复并更新主要活动

public class MainActivity extends Activity {

...
 lv = (ListView) findViewById(R.id.lv);
adapter = new Adapter(this, item);
lv .setAdapter(adapter);

...
}


但是如果用户已经在活动中,该如何更新呢?

最佳答案

您必须使用BroadcastReciever来完成此任务:http://developer.android.com/reference/android/content/BroadcastReceiver.html

活动中:

public class MainActivity extends Activity {
    public static final String NOTIFY_ACTIVITY_ACTION = "notify_activity";
    private BroadcastReciver broadcastReciver;


 @Override
protected void onStart() {
    super.onStart();
    broadcastReciver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction.equals(NOTIFY_ACTIVITY_ACTION ))
            {
             //to do smth
            }
        }
    }

    IntentFilter filter = new IntentFilter( NOTIFY_ACTIVITY_ACTION );
    registerReceiver(broadcastReciver, filter);
}

@Override
protected void onStop()
{
 unregisterReceiver(broadcastReciver);
}


}


服务中:

Intent broadcastIntent = new Intent();
broadcastIntent.setAction(MainActivity.NOTIFY_ACTIVITY_ACTION );
broadcastIntent.putExtra("addtional_param", 1);
broadcastIntent.putExtra("addtional_param2", 2); //etc

sendBroadcast(broadcastIntent);


更新

顺便说一句,最好使用LocalBroadcastManager在应用程序内发送广播。它使用与普通广播相同的方式,但首先创建LocalBroadcastManager:

LocalBroadcastManager manager = LocalBroadcastManager.getInstance(MainActivity.this);


并在onStart中:

manager.registerReciever(broadcastReciver, filter);


并在onStop中:

manager.unregisterBroadcast(broadcastReciver);


并在服务中:

manager.sendBroadcast(broadcastIntent);

10-07 19:33
查看更多