[英]How can i create a broadcast receiver?
This is my first time using the stackoverflow I am creating a chat program but only coding the broadcast receiver and receiving message notification left. 这是我第一次使用stackoverflow创建聊天程序,但仅编码广播接收器并接收消息通知。 I created an exampleapp for my intent but it only works when app is open.
我出于自己的意图创建了一个exampleapp,但仅在打开该应用时才有效。 How can i simply create a broadcast receiver?
我如何简单地创建广播接收器?
I am not getting error 我没有收到错误
My MainActivity: 我的主要活动:
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();
}
}
(I did not added my other codes because i am getting error and i can not solve because i am coding on android) (我没有添加其他代码,因为我遇到了错误,我无法解决,因为我正在android上进行编码)
My 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();
}
}```
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.