gpt4 book ai didi

java - 如何创建广播接收器?

转载 作者:行者123 更新时间:2023-12-02 03:33:02 25 4
gpt4 key购买 nike

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

我没有收到错误

我的主要 Activity :

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 上编码)

最佳答案

我的 Intent :


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();
}
}```

关于java - 如何创建广播接收器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56875001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com