intentservice无法正常运行

时间:2018-07-10 11:53:19

标签: java android android-studio

我制作了一个小应用,可以接收铃声模式更改广播,然后在收到时显示一个小吐司。尽管仅使用一个活动即可实现,但我打算使用intentservice。但是,我所做的intentservice每次都使应用程序崩溃,而且还没有成功运行过一次。

MainActivity.java文件:

request(
  {
    url: "https://self.wavity.net/scim/doc/",
    auth: {
      bearer: accessToken
    }
  },
  function(err, res) {
    //do something
  }
);

AudioService.java文件

package com.example.android.servicepractice;

import android.content.ComponentName;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent serviceIntent = new Intent();
serviceIntent.setAction("com.example.android.servicepractice.AudioService");
    startService(serviceIntent);

}
}

AndroidManifest.xml文件

package com.example.android.servicepractice;

import android.app.IntentService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.widget.Toast;

public class AudioService extends IntentService{

public BroadcastReceiver receiver;

//First requirement is a constructor
public AudioService(){
    super("AudioService");
}

//This is the function that is called when the service is created
@Override
public void onHandleIntent(Intent intent){
    //Work that needs to be done
    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(getApplicationContext(), "Audio Mode Changed", Toast.LENGTH_SHORT).show();
        }
    };

    IntentFilter filter = new IntentFilter(AudioManager.RINGER_MODE_CHANGED_ACTION);
    registerReceiver(receiver, filter);
    }
 }

我是android的新手,这是我第一次使用intentservices,所以我想知道在这里使用Services或IntentServices会是更好的选择吗?另外,该应用程序继续崩溃的原因是什么?

0 个答案:

没有答案