我想检查当前正在运行的应用程序是否匹配显示消息。 这是我的服务代码
public class MyService extends Service{
Context context;
ActivityManager am ;
List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo;
Dbheltool db;
String packname;
String key;
HashMap<String, String> list;
public MyService(Context context) {
// TODO Auto-generated constructor stub4
this.context=context;
db=new Dbheltool(context);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this, "The new Service was Created", Toast.LENGTH_LONG).show();
am = (ActivityManager) getSystemService(context.ACTIVITY_SERVICE);
runningAppProcessInfo = am
.getRunningAppProcesses();
try{
db.open();
list=(HashMap)db.getPackage();
db.close();
}catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
Toast.makeText(context, "Exception", Toast.LENGTH_SHORT);
}
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();
if(isThisApplicationRunning(context)){
Toast.makeText(context, "Success", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
public boolean isThisApplicationRunning(final Context context) {
for (final RunningAppProcessInfo app : runningAppProcessInfo) {
try{
if(list.get(app.processName.toString()).equals(app.processName.toString())) {
return true
}
}
catch(NullPointerException e){
}
}
return false;
}
}
当我运行这个应用程序时它失败并给出Nullpointer异常并且服务停止...请帮助我如何做到这一点。 我的服务目标是....&#34;我的服务在后台运行,并检查用户运行的应用程序。当用户点击任何应用程序时。服务检查应用程序包它匹配Hashmap对象,如果它找到hashmap对象的键和值匹配它显示吐司的当前正在运行的应用程序的包名称&#34;
答案 0 :(得分:0)
nullpointer看起来像是来自你的行:
if (list.get(app.processName).equals(app.processName)) {
您的比较声明似乎是在比较不存在的值?
另请参阅Kkudi的答案:Android: how do I check if activity is running?
它可以帮助您构建方法。