Android - 服务无法启动

时间:2016-01-16 13:25:58

标签: java android android-service startup

我正在为我和我的同学们制作应用程序,检查新的作业和考试。由于检查学校服务器(如每5分钟)更改了文件大小和检查列表以及这样的东西,它有可能不会被杀死的服务。我尝试了以下代码:

MayinActivity.java

package com.test.simpleservice;

import android.app.ActivityManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.util.List;

public class MainActivity extends AppCompatActivity {
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


//checking runings services - remove later
    ActivityManager am = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningServiceInfo> rs = am.getRunningServices(50);
    String message = null;

    for (int i=0; i<rs.size(); i++) {
        ActivityManager.RunningServiceInfo
                rsi = rs.get(i);
        System.out.println("!!!!!!!!!!Service" + "Process " + rsi.process + " with component " + rsi.service.getClassName());
        message = message + rsi.process;
    }


    Button btnStart = (Button) findViewById(R.id.startBtn);
    btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ServiceManager.startService(getApplicationContext());

            }
        });

    }

}

MyServices.java

package com.test.simpleservice;

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

public class MyServices extends Service {

    private static final String LOGTAG = "MyServices";

    @Override
    public void onStart(Intent intent, int startId) {
        System.out.println("start...");
        //some code of your service starting,such as establish a connection,create a TimerTask or something else
        Toast.makeText(this, "service start", Toast.LENGTH_LONG).show();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //this will start service
        System.out.println("startcommand...");
        Toast.makeText(this, "service startcomand", Toast.LENGTH_LONG).show();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        //this will NOT kill service
        //super.onDestroy();
        Toast.makeText(this, "task destroyed", Toast.LENGTH_LONG).show();
        Intent in = new Intent();
        in.setAction("PreventKilling");
        sendBroadcast(in);
    }

    @Override
    public void onTaskRemoved(Intent intent){
        Toast.makeText(this, "task removed", Toast.LENGTH_LONG).show();
        intent = new Intent(this, this.getClass());
        startService(intent);
    }


}

Reciever.java

package com.test.simpleservice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;


public class Receiver extends BroadcastReceiver {
    private static final String LOGTAG = "Receiver";
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            Intent serviceIntent = new Intent(context, MyServices.class);
            context.startService(serviceIntent);
        }

        Log.d(LOGTAG, "ServiceDestroy onReceive...");
        Log.d(LOGTAG, "action:" + intent.getAction());
        Log.d(LOGTAG, "ServiceDestroy auto start service...");
        ServiceManager.startService(context);
    }

}

的ServiceManager

package com.test.simpleservice;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class ServiceManager {
    private static final String LOGTAG = "ServiceManager";

    public static void startService(Context context) {
        Log.i(LOGTAG, "ServiceManager.startSerivce()...");
        Intent intent = new Intent(MyServices.class.getName());
        intent.setPackage("com.test.simpleservice");
        context.startService(intent);
    }

}

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.simpleservice">

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyServices" />

        <receiver android:name=".Receiver" >
            <intent-filter>
                <action android:name="PreventKilling" />    
            </intent-filter>

            <intent-filter>
                <action android:name="android.intent.action.RECIEVE_BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>

    </application>

</manifest>

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.test.simpleservice.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/start_btn"
        android:id="@+id/startBtn"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

当我运行应用程序并单击“开始”按钮时,服务将无法启动 - 没有敬酒,没有日志,设置中没有任何内容 - >应用程序 - >服务。为什么?没有恼人通知的任何更好的方法来制作不可杀戮的过程?

logcat的 最后几行因为之前刚刚列出的服务:

01-16 14:10:15.567 13753-13772/com.test.simpleservice I/OpenGLRenderer: Initialized EGL, version 1.4
01-16 14:10:15.567 13753-13772/com.test.simpleservice W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
01-16 14:10:15.587 13753-13772/com.test.simpleservice D/OpenGLRenderer: Enabling debug mode 0
01-16 14:10:17.597 13753-13753/com.test.simpleservice I/ServiceManager: ServiceManager.startSerivce()...

还有一个问题:这个应用程序会在启动后启动吗?如果没有,我做错了什么?

对不起我的英语不好

1 个答案:

答案 0 :(得分:1)

Intent intent = new Intent(context, MyServices.class);
        intent.setPackage("com.test.simpleservice");
        context.startService(intent);

因为您的上下文是:

 public static void startService(Context context)

在这里:

 public void onReceive(Context context, Intent intent)

对于上述Intent名称 - &gt;的意图