创建一个接收关闭广播的服务,如下所示:
public class MyAppShutdown extends BroadcastReceiver{
private static final String TAG = "MyAppShutdown";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.v(TAG, "onReceive - ++ ENTER ++");
if (intent != null && intent.getAction().equals(Intent.ACTION_SHUTDOWN)){
Log.v(TAG, "onReceive - ***] SHUTDOWN [***");
// perhaps send a broadcast to your app via intent to perform a log out.
Intent intent = new Intent();
intent.addAction("intent.myapp.action.shutdown");
sendBroadcast(intent);
}
Log.v(TAG, "onReceive - ++ LEAVE ++");
}
}
在您的AndroidManifest.xml
中,将以下片段嵌入<application>
标签中:
<receiver android:name=".MyAppShutdown">
<intent-filter>
<action android:name="android.intent.action.SHUTDOWN"/>
</intent-filter>
</receiver>
从您的应用程序的活动中注册一个广播接收器,该接收器具有适当的意图过滤器:
public class myApp extends Activity{
private myAppBroadcastRcvr myAppRcvr = new myAppBroadcastRcvr();
@Override
public void onCreate(Bundle savedInstanceState){
IntentFilter filter = new IntentFilter();
filter.addAction("intent.myapp.action.shutdown");
registerReceiver(myAppRcvr, filter);
}
// Perhaps you have this
private void LogOff(){
}
class myAppBroadcastRcvr extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent){
if (intent.getAction().equals("intent.myapp.action.shutdown")){
LogOff();
}
}
}
}