简体   繁体   English

Android-服务无法启动

[英]Android - Service does not start

I am making app for me and my class mates, that checks for new homeworks and exams. 我正在为我和我的班级同伴制作应用程序,用于检查新的作业和考试。 It has service that may not be killed beacuse of checking school server (like every 5 minutes) for changed size of file with list of exams and stuff like this. 它具有无法通过检查学校服务器(例如每5分钟)以检查文件和诸如此类的内容来更改文件大小的服务。 I tried following code: 我尝试了以下代码:

MayinActivity.java 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 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 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 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>

When I run the app and click button "start", the service wont start - no toasts, no logs, nothing in setting->apps->services. 当我运行该应用程序并单击“启动”按钮时,该服务将不会启动-没有举杯,没有日志,在设置->应用程序->服务中什么也没有。 Why? 为什么? Any better way to make unkillable process without anoying notification? 在不引起通知的情况下进行更好的处理的更好方法吗?

logcat last few lines becouse that before are just listed services: 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()...

And one more question: will this app start after boot? 还有一个问题:该应用在启动后会启动吗? If not, what did I do wrong? 如果没有,我做错了什么?

im sorry for my poor english 我为我的英语不好对不起

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

Because your context is: 因为您的上下文是:

 public static void startService(Context context)

And here : 和这里 :

 public void onReceive(Context context, Intent intent)

For above Intent name -> intent 对于以上Intent名称-> intent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM