gpt4 book ai didi

android - 启动广播接收器类

转载 作者:行者123 更新时间:2023-11-30 04:18:28 25 4
gpt4 key购买 nike

我正在创建一个 SMS 涉水应用程序。我目前有两个类(class);将用于修改设置的主要 Activity 类和使用 BroardcastReceiver 的 smsListener 类。但是,我不知道如何启动 smsListener 类。ref 的 smsListener 类代码

package sms.pack;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.SmsMessage;
import android.util.Log;

public class SmsListener extends BroadcastReceiver{

private SharedPreferences preferences;

@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub

if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
Bundle bundle = intent.getExtras(); //---get the SMS message passed in---
SmsMessage[] msgs = null;
String device = "mobile_num_here"; //number to listen for
String msg_from;
if (bundle != null){
//---retrieve the SMS message received---
try{
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msg_from = msgs[i].getOriginatingAddress();
String msgBody = msgs[i].getMessageBody();
if (msg_from == device)
{
savedata(msgBody);
}
}
}catch(Exception e){
// Log.d("Exception caught",e.getMessage());
}
}
}
}
public void savedata(String data)
{
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
File gpxfile = new File(root, "smsfile.txt");//remember change directory
FileWriter gpxwriter = new FileWriter(gpxfile);
BufferedWriter out = new BufferedWriter(gpxwriter);
out.write(data);
out.close();
}
} catch (IOException e) {
Log.e(data,"Could not write file " + e.getMessage());
}
}
}

我打算使用 intent 来启动,但它不起作用,方法如下

public void startListening(View view)
{
Intent i = new Intent();
i.setClassName("sms.pack","sms.pack.SmsListener");
startActivity(i);
}

最佳答案

您仅使用 startActivity 来启动 Activity。
BroadcastReceiver收听广播的 Intent 。使用 sendBroadcast(intentToBroadcast)。确保你把 receiver list 文件中的标记。

关于android - 启动广播接收器类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9627084/

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