简体   繁体   中英

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. I created an exampleapp for my intent but it only works when app is open. 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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM