How to start an application in android when mobile is switched ON?
-
16-04-2021 - |
Domanda
Hai i have a application using background service.its running clearly.If my mobile is switch off,my service is ound service off.when my application is started then only my background service is strated .i want to restart the service again when mobile switch off? is it possible? Anybody explain with code
update
public class loginForm extends Activity
{
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView (R.layout.login);
receiver = new ConnectionReceiver();
registerReceiver(receiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
private class ConnectionReceiver extends BroadcastReceiver{
private Timer mTimer;
private TimerTask mTimerTask;
@Override
public void onReceive(Context context, Intent intent) {
NetworkInfo info = intent.getParcelableExtra (ConnectivityManager.EXTRA_NETWORK_INFO);
if(null != info)
{
String state = getNetworkStateString(info.getState());
if(state.equals("Connected")){
mTimer = new Timer();
mTimerTask = new TimerTask() {
@Override
public void run() {
loginForm.this.runOnUiThread(new Runnable() {
@Override
public void run() {
//Toast.makeText(getBaseContext(), "Disenabled provider " + provider,
///Toast.LENGTH_SHORT).show();
try{
insertAllGpsInformation();
}
catch(Exception e)
{
Toast.makeText(getBaseContext(), "Your Net Connected or Not Login to Net"+"", Toast.LENGTH_LONG).show();
Log.e("Upload Picture Error:",e.getMessage());
}
}
});
}
};
mTimer.scheduleAtFixedRate(mTimerTask,180000,180000);
}
}
}
}
}
Soluzione
Register for the ACTION_BOOT_COMPLETED
(see here for details). Start your service on boot.
Altri suggerimenti
You should register a BroadcastReceiver and look for the BOOT_COMPLETED Intent.
Here is link with some details: http://androidgps.blogspot.com/2008/09/starting-android-service-at-boot-time.html
Did I understand your question correctly?
create Broadcast Receiver that with the Intent of BOOT COMPLETED Action.
please refer following links for more help :
You can use
public class BootReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
Log.i("BootReceiver :: Start Booting..");
Intent i = new Intent(context, StartService.class); // Start your service class
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
and use the broadcastreciever in androidmanifest.xml as
<receiver android:name=".receiver.BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>