单击强制停止时我遇到了运行服务的问题,当我重启我的手机时应该调用服务.我已经按照一些例子但我无法完成任务.任何人都可以指导我完成任务.
需要:
1.Service should run when force stop has been clicked from settings
2.Service should run when mobile has been restarted.
TestActivity.java
包com.testsearching;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class TestActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
startService(new Intent(this, ServiceTest.class));
}
}
ServiceTest.java
package com.testsearching;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class ServiceTest extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mTimer.schedule(timerTask, 2000, 2 * 1000);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
} catch (Exception e) {
e.printStackTrace();
}
return super.onStartCommand(intent, flags, startId);
}
private Timer mTimer;
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
Log.e("Log", "Running");
}
};
public void onDestroy() {
try {
mTimer.cancel();
timerTask.cancel();
} catch (Exception e) {
e.printStackTrace();
}
Intent intent = new Intent("com.android.techtrainner");
intent.putExtra("yourvalue", "torestore");
sendBroadcast(intent);
}
}
ReceiverCall.java
package com.testsearching;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class ReceiverCall extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Log.i("Service Stops", "Ohhhhhhh");
context.startService(new Intent(context, ServiceTest.class));;
Toast.makeText(context, "My start", Toast.LENGTH_LONG).show();
}
}
}
的Manifest.xml
package="com.testsearching"
android:versionCode="1"
android:versionName="1.0" >
android:minSdkVersion="14"
android:targetSdkVersion="16" />
android:allowBackup="true"
android:theme="@style/AppTheme" >
android:name="com.testsearching.TestActivity"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar" >
android:name="ReceiverCall"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >