bol*_*ing 10 java android google-cloud-messaging
我想知道如何检查我的应用程序是否已打开,并且当onMessage()从GCM 接收时,用户当前可以看到该应用程序.起初,我只是使用自己的boolean isVisible,但后来我意识到这不可靠,因为如果应用程序没有打开,我用来访问该标志的对象是null.虽然这本身可以用来看看应用程序是否开放,但似乎有点混乱.Android中是否有一种方法可以从系统级别以某种方式检查应用程序当前是否已打开,以及用户是否正在查看应用程序?请记住,应用程序可以在技术上运行,但不可见,因为用户最近按下"主页"按钮将其发送到后台.
@Override
protected void onMessage(Context arg0, Intent arg1) {
String turn = intent.getExtras().getString("turn");
if (turn.equals("yours"){
if (/*app is open*/){ <------------------ what can go here?
// dont generate a notification
// display something in the game instead
}
else{
// generate notification telling player its their turn
}
}
}
Run Code Online (Sandbox Code Playgroud)
rci*_*ati 17
我会使用订单广播来做到这一点.
在你的onMessage方法中:
Intent responseIntent = new Intent("com.yourpackage.GOT_PUSH");
sendOrderedBroadcast(responseIntent, null);
Run Code Online (Sandbox Code Playgroud)
在您的活动中:
public class YourActivity extends Activity {
final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//Right here do what you want in your activity
abortBroadcast();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//.....
}
@Override
protected void onPause() {
unregisterReceiver(mBroadcastReceiver);
super.onPause();
}
@Override
protected void onResume() {
IntentFilter filter = new IntentFilter("com.yourpackage.GOT_PUSH");
filter.setPriority(2);
registerReceiver(mBroadcastReceiver, filter);
super.onResume();
}
}
Run Code Online (Sandbox Code Playgroud)
另一个BroadcastReceiver
public class SecondReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//In this receiver just send your notification
}
}
Run Code Online (Sandbox Code Playgroud)
表现:
<activity
android:name=".YourActivity"
android:label="@string/app_name">
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".SecondReceiver">
<intent-filter
android:priority="1">
<action
android:name="com.yourpackage.GOT_PUSH" />
</intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)
基本上在onMessage你发送一个Intent 的方法中,YourActivity如果它正在运行并且在前台,则由内部注册的BroadcastReceiver首先接收,否则它被接收SecondReceiver.
使用 SharedPreferences 保存布尔值 isVisible,当您从首选项中获取值时,您可以添加默认值。
SharedPreferences settings = context.getSharedPreferences("NAME_XXX", Activity.MODE_PRIVATE);
settings.getBoolean("visible", false);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7455 次 |
| 最近记录: |