java - Android Studio 中的Service問題
問題描述
新手,在學(xué)習(xí)Service一開始就碰到了問題是根據(jù)教程做的,在開啟服務(wù)時(shí)閃退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() {}@Overridepublic void onCreate() { Log.i('LOG','onCreat'); super.onCreate();}@Overridepublic 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;@Overrideprotected 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);}@Overridepublic 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> <serviceandroid:name='.MyService'><intent-filter> <action android:name='MyService'/></intent-filter> </service></application>
</manifest>
Logcat 錯(cuò)誤提示: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
問題解答
回答1:Intent intent=new Intent('MyService');什么鬼?這個(gè)不管什么版本的android系統(tǒng)都無法調(diào)起來的,service啟動(dòng)的方式分文兩種,顯示調(diào)用和隱式調(diào)用:
1)顯示啟動(dòng):
Intent intent=new Intent(MainActivity.this,MyService.class);
通過class調(diào)起service,
2)隱式啟動(dòng):
Intent intent=new Intent('com.example.administrator.myhhhhh.MyService');
里面是service類的絕對(duì)路徑(帶有包名部分),需要注意的是隱式啟動(dòng)在android最新版本(5.0以上)已經(jīng)被棄用(由于安全問題),你需要對(duì)他進(jìn)行一些額外的處理(通過action獲取它的ComponentName屬性),以下提供你一個(gè)方式,代碼如下:
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 foundif (resolveInfo == null || resolveInfo.size() != 1) { LogUtils.debug('not found action like this ’com.hll.push.heartbeat’'); return;}// Get component info and create ComponentNameResolveInfo 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 reuseIntent explicitIntent = new Intent(mIntent);// Set the component to be explicitexplicitIntent.setComponent(component);context.startService(explicitIntent); }
祝你好運(yùn)~
回答2:Intent intent=new Intent(this,MyService.class);回答3:
自己的intent寫錯(cuò)了
相關(guān)文章:
1. 獲取上次登錄ip的原理是啥?2. 為什么點(diǎn)擊登陸沒反應(yīng)3. mysql報(bào)錯(cuò) unknown column ’a.plat’ in ON clause4. fetch_field_direct()報(bào)錯(cuò)5. phpstudy v8打開數(shù)據(jù)庫(kù)就出錯(cuò),而phpstudy 2018不會(huì)6. 在視圖里面寫php原生標(biāo)簽不是要迫不得已的情況才寫嗎7. 求救一下,用新版的phpstudy,數(shù)據(jù)庫(kù)過段時(shí)間會(huì)消失是什么情況?8. 為什么說非對(duì)象調(diào)用成員函數(shù)fetch()9. 沒有輸出結(jié)果,也沒有報(bào)錯(cuò)信息10. 請(qǐng)問下tp6框架的緩存在哪里設(shè)置,或者說關(guān)閉?
