可能重复:
尝试在 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);
}
}
}
比较SIM.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;
}
}
我希望应用程序在启动时启动 compareSIM 服务,在启动过程中,此服务将运行,因为当前连接的 SIM 卡 IMSI 将被检索并与已保存的 IMSI 匹配,一旦它们不同,用户将被带到登录布局。我想在启动过程中执行此操作,但未能执行...请在编码方面给我建议,谢谢