使用Java定义一个android APP, 1.在定义一个类里面监听广播MyBroadcastReceiver; 2.当收到MyBroadcastReceiver后,启动的service Modemdebugservice 3.同时定义一个5分钟的计时器,并在计时器5分钟结束后,停止modemdebugservice的运行; 4.定义一个属性监听Modemdebugservice,true的时候,Modemdebugservice开启,false的时候,Modemdebugservice关闭
时间: 2024-03-14 21:46:38 浏览: 51
好的,以下是一个示例代码:
```
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
public class MyActivity extends AppCompatActivity {
private MyBroadcastReceiver myBroadcastReceiver;
private boolean isModemDebugServiceEnabled = false;
private final int STOP_MODEM_DEBUG_SERVICE = 1;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case STOP_MODEM_DEBUG_SERVICE:
stopModemDebugService();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBroadcastReceiver = new MyBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter("com.example.mybroadcastreceiver.MY_BROADCAST");
registerReceiver(myBroadcastReceiver, intentFilter);
}
private class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("com.example.mybroadcastreceiver.MY_BROADCAST")) {
startModemDebugService();
startTimer();
}
}
}
private void startModemDebugService() {
if (!isModemDebugServiceEnabled) {
isModemDebugServiceEnabled = true;
Intent intent = new Intent(this, ModemDebugService.class);
startService(intent);
}
}
private void stopModemDebugService() {
if (isModemDebugServiceEnabled) {
isModemDebugServiceEnabled = false;
Intent intent = new Intent(this, ModemDebugService.class);
stopService(intent);
}
}
private void startTimer() {
mHandler.sendEmptyMessageDelayed(STOP_MODEM_DEBUG_SERVICE, 5 * 60 * 1000); // 5 minutes
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myBroadcastReceiver);
stopModemDebugService();
mHandler.removeMessages(STOP_MODEM_DEBUG_SERVICE);
}
}
```
其中,MyBroadcastReceiver 监听广播 "com.example.mybroadcastreceiver.MY_BROADCAST",当接收到广播时,启动 ModemDebugService 服务,并启动一个 5 分钟的计时器,在计时器结束时停止 ModemDebugService 服务。isModemDebugServiceEnabled 属性监听 ModemDebugService 服务的状态,当为 true 时表示服务正在运行,为 false 时表示服务已经停止。在 Activity 销毁时需要停止 ModemDebugService 服务并移除计时器的消息。
阅读全文