【问题标题】:How can i create a broadcast receiver?如何创建广播接收器?
【发布时间】:2019-11-14 10:21:53
【问题描述】:

这是我第一次使用 stackoverflow 我正在创建一个聊天程序,但只编码广播接收器并接收消息通知。我为我的意图创建了一个示例应用程序,但它仅在应用程序打开时才有效。我怎样才能简单地创建一个广播接收器?

我没有收到错误

我的主要活动:

package com.example.backgroundservice;

import android.app.Activity;
import android.os.Bundle;

import android.content.Intent;
import android.widget.Toast;

import com.example.backgroundservice.R;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  startService(new Intent(this, BackgroundService.class));

  Toast.makeText(this, "Intent Başladı!", Toast.LENGTH_LONG).show();

 }

}

(我没有添加其他代码,因为我收到错误并且我无法解决,因为我在 android 上编码)

【问题讨论】:

标签: java android android-intent broadcast receiver


【解决方案1】:

我的意图:


import android.app.Service;
import android.content.*;
import android.os.*;
import android.widget.Toast;

public class BackgroundService extends Service {

    public Context context = this;
    public Handler handler = null;
    public static Runnable runnable = null;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show();

        handler = new Handler();
        runnable = new Runnable() {
            public void run() {
                Toast.makeText(context, "Service is still running", Toast.LENGTH_LONG).show();
                handler.postDelayed(runnable, 10000);
            }
        };

        handler.postDelayed(runnable, 15000);
    }

    @Override
    public void onDestroy() {
        /* IF YOU WANT THIS SERVICE KILLED WITH THE APP THEN UNCOMMENT THE FOLLOWING LINE */
        //handler.removeCallbacks(runnable);
        Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
    }
}```

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多