我想为我的 Android 应用程序创建一个通知。当我在类中与其余代码一起运行它时,它工作正常,当我单击按钮时一切都会执行,并且通知工作正常。但是,由于有很多工作要做,因此当我单击按钮时应用程序运行缓慢。为了帮助实现这一点,我将通知部分分成了它自己的一个类,并在不同的线程上运行它。 我在线程或通知方面没有太多经验,我希望得到一些有关此问题的帮助。我应该将通知部分分成一个自己的类吗?
HomeActivity 类是调用线程启动的地方,单击按钮时使用 start() 方法:
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import Model.Data;
public class HomeActivity extends FragmentActivity {
private com.atmlocator.hooper.kenneth.atmlocator.Notification n;
public void addListenerOnButton() {
locationSpinner = (Spinner) findViewById(R.id.spinner1);
options1Spinner = (Spinner) findViewById(R.id.spinner2);
options2Spinner = (Spinner) findViewById(R.id.spinner3);
Button locate = (Button) findViewById(R.id.locateBtn);
locate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Context context = getApplicationContext();
String text = "Loading...";
//call notification thread here
n.start();
//rest of code here...
}
}
}
}
然后通知类是:
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
public class Notification extends FragmentActivity implements Runnable {
private Thread t;
private String name;
Context context;
Notification(String name, Context c)
{
this.name = name;
this.context = c;
}
public void run()
{
// Intent is triggered if the notification is selected
Intent intent = new Intent(context, HomeActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), intent, 0);
// Build notification
android.app.Notification not = new android.app.Notification.Builder(context)
.setContentTitle("Notification")
.setContentText("New email").setSmallIcon(R.drawable.atm)
.setContentIntent(pIntent).build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
not.flags |= android.app.Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, not);
}
public void start()
{
t = new Thread (this, name);
t.start ();
}
}
最佳答案
Should I be separating the notification part into a class of it's own?
这应该没有任何问题!
此外,您还应该在线程之外显示您的通知。 您可以使用处理程序来显示通知而不是线程
像这样:
}
....
// write this outside your code block
Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
showNotification();
}
};
// call it like this instead of thread start
mHandler.sendEmptyMessage(0);
查看此链接以获取更多信息:https://developer.android.com/training/multiple-threads/communicate-ui.html
关于java - 如何在另一个线程中创建 Android 通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32458273/