在我的应用中,每当收到推送通知时,我都会检查用户是否可以看到我的mainActivity做某事......
我有一个静态布尔值,在mainActivity的true
内设置为onResume
,而false
内有onPause
。
我应该在onMessage中做什么
@Override
protected void onMessage(Context context, Intent intent)
{
if(mainActivity == visible)
//do something inside mainactivity.. change text inside edittext
else
//do something else
}
任何见解?
答案 0 :(得分:1)
我不喜欢保持对活动的静态引用。我认为他们已经准备好在你身上爆炸了。因此,您将建议替代@TeRRo回答:
在您的全球BroadcastReceiver onMessage
上,您将发送您的活动将会收听的LocalBroadcast
。像这样:
private static final String ACTION_PUSH_RECEIVED = "com.myapp.mypackage.action.pushReceived";
public static final IntentFilter BROADCAST_INTENT_FILTER = new IntentFilter(ACTION_PUSH_RECEIVED);
@Override
protected void onMessage(Context context, Intent intent) {
Intent i = new Intent(ACTION_PUSH_RECEIVED);
i.putExtra( ... add any extra data you want... )
LocalBroadcastManager.getInstance(context).sendBroadcast(i);
}
现在我们让活动听听它:
@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(context)
.registerReceiver(mBroadcastReceiver, BroadcastReceiverClass.BROADCAST_INTENT_FILTER);
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(context)
.unregisterReceiver(mBroadcastReceiver);
super.onPause();
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent){
// read any data you might need from intent and do your action here
}
}
答案 1 :(得分:0)
为避免这种情况,您应该管理活动参考。在清单文件中添加应用程序的名称:
<application
android:name=".MyApp"
....
</application>
您的申请类:
public class MyApp extends Application {
public void onCreate() {
super.onCreate();
}
private Activity mCurrentActivity = null;
public Activity getCurrentActivity(){
return mCurrentActivity;
}
public void setCurrentActivity(Activity mCurrentActivity){
this.mCurrentActivity = mCurrentActivity;
}
}
创建一个新活动:
public class MyBaseActivity extends Activity {
protected MyApp mMyApp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMyApp = (MyApp)this.getApplicationContext();
}
protected void onResume() {
super.onResume();
mMyApp.setCurrentActivity(this);
}
protected void onPause() {
clearReferences();
super.onPause();
}
protected void onDestroy() {
clearReferences();
super.onDestroy();
}
private void clearReferences(){
Activity currActivity = mMyApp.getCurrentActivity();
if (currActivity != null && currActivity.equals(this))
mMyApp.setCurrentActivity(null);
}
}
因此,现在不是为您的活动扩展Activity类,而是扩展MyBaseActivity。现在,您可以从应用程序或活动上下文中获取当前活动:
Activity currentActivity = ((MyApp)context.getApplicationContext()).getCurrentActivity();
答案 2 :(得分:0)
或者,当您收到推送通知时,为什么不使用本地广播,并在活动中接收推送通知,并进行相应的更改或操作。
如果它们是UI密集型任务,请将您的活动绑定到服务,并接收推送通知并在此服务中执行操作并使用活动中的结果。