问:需要从仅安装当前服务而不处于运行状态的另一个应用程序启动后台服务。因此,我通过使用onCreate方法中MainActivity类中的以下代码从另一个应用程序启动了服务:
static Context mconrtext;
static Context mpconrtext;
@Override
public void onCreate(Bundle savedInstanceState)
{
int flag = 0;
int flagM = 0;
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
{
if ("com.GeoFencing.android.androidservice.MyService".equals(service.service.getClassName())){
flag = 1;
}
if ("com.Misper.android.Notification.MyService".equals(service.service.getClassName())){
flagM = 1;
}
try
{
if(flag == 0){
this.mconrtext=this;
Intent i = new Intent();
i.setComponent(new ComponentName("com.GeoFencing.android.androidservice", "com.GeoFencing.android.androidservice.LaunchTracker"));
mconrtext.startService(i);
}
}
catch(Exception exe)
{
}
try
{
if(flagM == 0){
mpconrtext=this;
Intent j = new Intent();
j.setComponent(new ComponentName("com.Misper.android.Notification", "com.Misper.android.Notification.LaunchMPush"));
mpconrtext.startService(j);
}
}
catch(Exception exe)
{
}
}
通过添加以下代码更新了AndroidManifest.xml:
<service android:enabled="true"
android:exported = "true"
android:name="com.GeoFencing.android.androidservice.LaunchTracker">
<intent-filter>
<action android:name="com.GeoFencing.android.androidservice.LaunchTracker" />
</intent-filter>
</service>
<service android:enabled="true"
android:exported = "true"
android:name="com.Misper.android.Notification.LaunchMPush">
<intent-filter>
<action android:name="com.Misper.android.Notification.LaunchMPush" />
</intent-filter>
</service>
在LaunchMpush类的后台服务中,我添加了以下代码
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class LaunchMPush extends Service {
static int Timervalue=120;
public static Context mContex;
static DisplayUiLisner displayLisner;
private PendingIntent pendingIntent;
private AlarmManager manager;
static double course ;
static int TimerIntervalVal=120;
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
mContex =this;
}
public static void setLisnerDisplay(DisplayUiLisner setDisplayLisner){
displayLisner =setDisplayLisner;
}
@Override
public void onStart(Intent intent, int startId) {
Intent dialogIntent = new Intent(mContex,MainActivity.class);
//dialogIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);
}
@Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
现在:1.应用程序正在启动后台服务,并且正在盯着服务,因此没有问题。 2.问题是启动后台服务并且用户关闭这些后台服务的UI时,这些服务的UI会继续打开它的框。请帮助我解决此问题。
答:你这个代码没有什么问题的。