我正在尝试制作锁定屏幕,所以我在它的广播接收器和 MainActivity 中创建了服务类 n。它一直工作到屏幕关闭,当屏幕打开时,主要活动关闭并显示异常。请帮我解决它。
我的服务.java
package com.example.broadcast_receiver;
import android.app.Service;
...
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
Log.i("[myService]", "onCreate");
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_ON));
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_OFF));
}
@Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.i("[myService]", "onStart");
}
@Override
public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
Log.i("[myService]", "onDestroy");
}
BroadcastReceiver mybroadcast = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i("[BroadcastReceiver]", "MyReceiver");
if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
Log.i("[BroadcastReceiver]", "Screen ON");
Intent i=new Intent(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
context.startActivity(i);
}
else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
Log.i("[BroadcastReceiver]", "Screen OFF");
}
}
};
}
MainActivity.java
package com.example.broadcast_receiver;
import android.os.Bundle;
...
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("[MainActivity]", "Created");
try{
boolean a=isMyServiceRunning();
if(a==false){
startService(new Intent(this,MyService.class));
}
}catch (Exception e) {
// TODO: handle exception
Log.i("Error", e.getMessage().toString());
Toast.makeText(this, e.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (MyService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
AndroidManifest.xml(未添加用户权限)
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<service android:name="com.example.broadcast_receiver.MyService"
android:label="@string/app_name"
android:icon="@drawable/ic_launcher" ></service>
<activity
android:name="com.example.broadcast_receiver.MainActivity"
android:label="@string/app_name"
android:launchMode="singleTop" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
请帮我解决dis问题。