java - Android Studio 中的Service问题

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

问题描述

问 题

新手,在学习Service一开始就碰到了问题
是根据教程做的,在开启服务时闪退
MyService.java

package com.example.administrator.myhhhhh;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {

public MyService() {
}

@Override
public void onCreate() {
    Log.i("LOG","onCreat");
    super.onCreate();
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}

}

MainActivity.java

package com.example.administrator.myhhhhh;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

private Button start,stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button start=(Button)findViewById(R.id.button);
    Button stop=(Button)findViewById(R.id.button2);
    start.setOnClickListener(this);
    stop.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    Intent intent=new Intent("MyService");
    switch (v.getId()){
        case R.id.button:
            startService(intent);
            break;
        case R.id.button2:
            stopService(intent);
            break;
    }
}

}

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

package="com.example.administrator.myhhhhh">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    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=".MyService"
        >
        <intent-filter>
            <action android:name="MyService"/>
        </intent-filter>
    </service>
</application>

</manifest>

Logcat 错误提示:
05-04 21:28:44.377 21214-21214/com.example.administrator.myhhhhh E/AndroidRuntime: FATAL EXCEPTION: main

                                                                               Process: com.example.administrator.myhhhhh, PID: 21214
                                                                               java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=MyService }
                                                                                   at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:1851)
                                                                                   at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1880)
                                                                                   at android.app.ContextImpl.startService(ContextImpl.java:1864)
                                                                                   at android.content.ContextWrapper.startService(ContextWrapper.java:516)
                                                                                   at com.example.administrator.myhhhhh.MainActivity.onClick(MainActivity.java:26)
                                                                                   at android.view.View.performClick(View.java:4918)
                                                                                   at android.view.View$PerformClick.run(View.java:20399)
                                                                                   at android.os.Handler.handleCallback(Handler.java:815)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                                   at android.os.Looper.loop(Looper.java:194)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5871)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1119)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)

05-04 21:28:44.434 21214-21214/com.example.administrator.myhhhhh I/Process: Sending signal. PID: 21214 SIG: 9

解决方案

Intent intent=new Intent("MyService");什么鬼?这个不管什么版本的android系统都无法调起来的,service启动的方式分文两种,显示调用和隐式调用:

1)显示启动:

Intent intent=new Intent(MainActivity.this,MyService.class);

通过class调起service,

2)隐式启动:

Intent intent=new Intent("com.example.administrator.myhhhhh.MyService");

里面是service类的绝对路径(带有包名部分),需要注意的是隐式启动在android最新版本(5.0以上)已经被弃用(由于安全问题),你需要对他进行一些额外的处理(通过action获取它的ComponentName属性),以下提供你一个方式,代码如下:

 protected static synchronized void startService(Context context,String action){
        LogUtils.debug("startHeartBeatService.");
        if (context==null){
            throw new NullPointerException("context must not be null.");
        }
        //add Urgent listener service.
        Intent mIntent=new Intent();
        mIntent.setAction(action);
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> resolveInfo = pm.queryIntentServices(mIntent, 0);
        // Make sure only one match was found
        if (resolveInfo == null || resolveInfo.size() != 1) {
            LogUtils.debug("not found action like this \'com.hll.push.heartbeat\'");
            return;
        }
        // Get component info and create ComponentName
        ResolveInfo serviceInfo = resolveInfo.get(0);
        String packageName = serviceInfo.serviceInfo.packageName;
        String className = serviceInfo.serviceInfo.name;
        ComponentName component = new ComponentName(packageName, className);
        // Create a new intent. Use the old one for extras and such reuse
        Intent explicitIntent = new Intent(mIntent);
        // Set the component to be explicit
        explicitIntent.setComponent(component);
        context.startService(explicitIntent);
    }

祝你好运~

这篇关于java - Android Studio 中的Service问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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