开始曾经 运行 服务

Start ever running Service

我想在 android 中启动一个永远 运行 的服务,检查哪个应用程序在后台。如果前台应用程序在我的应用程序的数据库中,那么它会打开密码屏幕以输入密码。

我的成就是,只要应用程序是 运行,我的服务就会运行,但是当我停止应用程序(将其从以前的应用程序中删除)时,我的服务就会停止。我可以在不输入密码的情况下打开锁定的应用程序。我在互联网上尝试了很多解决方案,但 none 似乎有效。请帮助我,

package services;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.antzion.salmanali.lockapp.FeedReaderContract;
import com.antzion.salmanali.lockapp.FeedReaderDBHelper;
import com.antzion.salmanali.lockapp.PasswordSet;
import com.antzion.salmanali.lockapp.Pattern;

/**
 * Created by Salman Majid Ali on 12/26/2016.
 */

public class TestService extends Service {
String [] names;
FeedReaderDBHelper helper;
private AppChecker appChecker;
private String currentLocked = "";
Detector detector;

public TestService()
{
    if(Utils.postLollipop())
        detector = new LollipopDetector();
    else
        detector = new PreLollipopDetector();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(getApplicationContext(), "service Start", Toast.LENGTH_SHORT).show();
    System.out.println("StartRemove");
    helper = new FeedReaderDBHelper(this);
    names = helper.getNames();
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            if(!AppChecker.running)
            {
                startChecker();
            }
        }
    });
    t.start();

    return START_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onTaskRemoved(Intent rootIntent) {
    System.out.println("Remove");
    Intent restart=new Intent(getApplicationContext(),this.getClass());
    restart.setPackage(getPackageName());
    startService(restart);
    super.onTaskRemoved(rootIntent);
}
@Override
public    void onDestroy()
{
    Intent restart=new Intent(getApplicationContext(),this.getClass());
    restart.setPackage(getPackageName());
    startService(restart);
    super.onDestroy();
}

private void startChecker()
{
    appChecker = new AppChecker();
    appChecker
            .when(getPackageName(), new AppChecker.Listener() {
                @Override
                public void onForeground(String packageName) {
                    //Toast.makeText(getBaseContext(), "Our app is in the foreground.", Toast.LENGTH_SHORT).show();
                }
            })
            .other(new AppChecker.Listener() {
                @Override
                public void onForeground(String packageName) {
                    //System.out.println("Foreground " + packageName);
                    //System.out.println("In Other " + setting.getBooleanValue(PrefVars.onlock) + " " +  setting.getBooleanValue(PrefVars.onLock3) +
                    //        " " + setting.getBooleanValue(PrefVars.lockImmediately));
                    try {

                        if(currentLocked != null && !packageName.equals(currentLocked)
                                && !helper.isLocked(currentLocked)
                                && helper.getValue(FeedReaderContract.FeedEntry.onexit).equals("YES"))
                        {
                            Log.i("Locking ", currentLocked);

                            helper.lock(currentLocked);
                        }
                        if(helper.getPackageName(packageName))
                        {
                            //System.out.println(packageName + "App is in the Database");
                            if(helper.isLocked(packageName))
                            {
                                System.out.println("UnLocking " + packageName);
                                getPassword(packageName);
                                currentLocked = packageName;

                            }
                        }
                    }catch(Exception e)
                    {

                    }

                    //Toast.makeText(getBaseContext(), "Foreground: " + packageName, Toast.LENGTH_SHORT).show();
                }
            })
            .start(this);
}

private void getPassword(String pack)
{
    int i = helper.getPassOrPat();
    boolean pass = false;
    if(i == 1)
        pass = true;
    else
        pass = false;

    if(pass)
    {
        Intent intent = new Intent(this, PasswordSet.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("PASS", pack);
        intent.putExtra("CONFIRM", "YES");
        startActivity(intent);
    }
    else
    {
        Intent intent = new Intent(this, Pattern.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("PASS", pack);
        intent.putExtra("CONFIRM", "YES");
        startActivity(intent);
    }

}

}

如果您需要,我可以提供 AppChecker class 的代码。请让我知道我应该怎么做才能达到预期的结果。我会很感激你的。

如果服务由您的应用程序启动,它将 运行 在您的应用程序进程中,一旦应用程序被终止,服务也会被终止。你可以做的是在你的服务的 onTaskRemoved 方法中,把这个

Intent intent = new Intent("com.whatever.restartservice");
 sendBroadcast(intent);

并在服务本身和 onReceive 中设置广播接收器,重新启动服务。我已经测试过,每次应用程序被杀死时它都能正常工作。

编辑: 试试这个

 @Override public void onTaskRemoved(Intent rootIntent){
     Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());

     PendingIntent restartServicePendingIntent = PendingIntent.getService(
         getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
     AlarmManager alarmService = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
     alarmService.set(ELAPSED_REALTIME, elapsedRealtime() + 1000,
         restartServicePendingIntent);

     super.onTaskRemoved(rootIntent); 
}

无论它如何被杀死,它都会重新启动你的服务

要启动 运行ning 服务,您必须在清单中定义您的服务,如

<service
        android:name=".service.youservice"
        android:exported="true"
        android:process=":ServiceProcess" />

通过使用它,您的服务将 运行 在 ServiceProcess 的另一个进程上。

将长 运行ning 服务定义为

的步骤很少
  • onStartCommand() return START_STICKY
  • 在服务的onDestroy()中自启动
  • 创建守护服务
  • 创建本机守护进程 (jin)