Android-服务无法启动 [英] Android - Service does not start

查看:461
本文介绍了Android-服务无法启动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我和我的班级同伴制作应用程序,用于检查新的作业和考试.它具有无法通过检查学校服务器(例如每5分钟一次)以检查文件和诸如此类的内容来更改文件大小的服务.我尝试了以下代码:

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

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

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 最后几行是因为之前只是列出的服务:

logcat last few lines becouse that before are just listed services:

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?

为我的英语不好对不起

推荐答案

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名称-> 意图

这篇关于Android-服务无法启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆