我有一個廣播接收器,當某個事件發生時,即使應用程序沒有運行,我也想運行一些代碼。如何在應用程序關閉時檢測廣播接收器?
我的代碼如下所示
MainActivity.java
package kenneth.menuactivator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textchange;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textchange = (TextView)findViewById(R.id.text);
}
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
broadcastIntent();
textchange.setText("Menu Pressed");
return true;
}
return super.onKeyLongPress(keyCode,event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
event.startTracking();
return true;
}
return super.onKeyDown(keyCode,event);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void broadcastIntent()
{
Intent intent = new Intent();
intent.setAction("kenneth.menuactivator.CUSTOM_INTENT");
sendBroadcast(intent);
}
}
Receiver.java
package kenneth.menuactivator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//some code
}
}
我在清單添加的許可。該代碼正常運行時,該代碼正常工作。但該應用程序已關閉,它不起作用。或者是否有任何其他方式可以檢測事件,即使應用程序未運行。
使用粘性boradcast – Raghunandan