可能重複:
Trying to start a service on boot on Android如何在設備啓動時啓動服務?
廣播接收器
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class StartActivityAtBoot extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent i = new Intent(context, CompareIMSI.class);
context.startService(i);
}
}
}
CompareSIM.java
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class CompareIMSI extends Service{
Context context;
TelephonyManager operator;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
//compareSIM();
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
compareSIM();
}
public void compareSIM(){
final String STORAGE = "Storage";
SharedPreferences unique = getSharedPreferences(STORAGE, 0);
final String storedIMSI = unique.getString("simIMSI", "");
final String currentIMSI = getSubscriberId().toString();
if (!storedIMSI.equals(currentIMSI)){
Intent i = new Intent(CompareIMSI.this, ScreenLockActivity.class);
startActivity(i);
}
}
public String getSubscriberId(){
String IMSI = null;
String serviceName = Context.TELEPHONY_SERVICE;
TelephonyManager m_telephonyManager = (TelephonyManager) getSystemService(serviceName);
IMSI = m_telephonyManager.getSubscriberId();
return IMSI;
}
}
我想日e應用程序啓動時啓動compareSIM服務,在啓動過程中,此服務將運行,因爲當前連接的SIM卡IMSI將被檢索並與已保存的IMSI匹配,一旦它們不同,用戶將被帶入登錄佈局。我想引導期間執行此,但未能如願......請諮詢我的編碼,感謝
當您運行此代碼時發生了什麼? –
你的服務正在啓動或不啓動? –