gpt4 book ai didi

java - 通知后从服务刷新 Activity

转载 作者:行者123 更新时间:2023-11-30 09:04:26 24 4
gpt4 key购买 nike

我有服务

public class GcmIntentService extends IntentService{...}

管理通知。如果用户不在应用程序中,当通知到达时,点击通知,主要 Activity 将恢复并更新

public class MainActivity extends Activity {

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

...
}

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

最佳答案

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

在 Activity 中:

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

关于java - 通知后从服务刷新 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25205813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com