所以,我的应用程序有BroadcastReceiver并接收来自其他应用程序的通知。问题是,我收到一条消息,通过Toast在手机中显示它,但我想在TextView上显示它。我的整个应用程序中只有两个课程。
我的接收器是我自己的类,它扩展了BroadcastReceiver,它的onReceive方法如下所示:
public void updateTheTextView(final String textFromNotification) {
final Context context = this;
Toast toast = Toast.makeText(context, "Message received: " + textFromNotification, Toast.LENGTH_LONG);
toast.show();
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
textV1.setText(textFromNotification);
}
});
}
这是更新textView的方法的代码。此方法位于MainActivity类中:
# define the numbers of nodes in hidden layers
nodesLayer1 = 500
nodesLayer2 = 500
nodesLayer3 = 500
# define our goal class
classes = 2
batchSize = 500
# x for input, y for output
sizeOfRow = len(data[0])
x = tensorFlow.placeholder(dtype= "float", shape=[None, sizeOfRow])
y = tensorFlow.placeholder(dtype= "float")
def neuralNetworkModel(data):
# first step: (input * weights) + bias, linear operation like y = ax + b
# each layer connection to other layer will represent by nodes(i) * nodes(i+1)
hiddenLayer1 = {"weights" : tensorFlow.Variable(tensorFlow.random_normal([sizeOfRow, nodesLayer1])),
"biases" : tensorFlow.Variable(tensorFlow.random_normal([nodesLayer1]))}
hiddenLayer2 = {"weights" : tensorFlow.Variable(tensorFlow.random_normal([nodesLayer1, nodesLayer2])),
"biases" : tensorFlow.Variable(tensorFlow.random_normal([nodesLayer2]))}
hiddenLayer3 = {"weights": tensorFlow.Variable(tensorFlow.random_normal([nodesLayer2, nodesLayer3])),
"biases": tensorFlow.Variable(tensorFlow.random_normal([nodesLayer3]))}
outputLayer = {"weights": tensorFlow.Variable(tensorFlow.random_normal([nodesLayer3, classes])),
"biases": tensorFlow.Variable(tensorFlow.random_normal([classes]))}
# create the layers
layer1 = tensorFlow.add(tensorFlow.matmul(data, hiddenLayer1["weights"]), hiddenLayer1["biases"])
layer1 = tensorFlow.nn.relu(layer1) # pass values to activation function (i.e sigmoid, softmax) and add it to the layer
layer2 = tensorFlow.add(tensorFlow.matmul(layer1, hiddenLayer2["weights"]), hiddenLayer2["biases"])
layer2 = tensorFlow.nn.relu(layer2)
layer3 = tensorFlow.add(tensorFlow.matmul(layer2, hiddenLayer3["weights"]), hiddenLayer3["biases"])
layer3 = tensorFlow.nn.relu(layer3)
output = tensorFlow.matmul(layer3, outputLayer["weights"]) + outputLayer["biases"]
return output
def neuralNetworkTrain(x):
prediction = neuralNetworkModel(x)
# using softmax function, normalize values to range(0,1)
cost = tensorFlow.reduce_mean(tensorFlow.nn.softmax_cross_entropy_with_logits(prediction, y))
# minimize the cost function
# at the same way we can use Gradiant Decent
# default learning rate is 0.001 in AdamOptimizer
optimizer = tensorFlow.train.AdamOptimizer(0.0001).minimize(cost)
epochs = 15
# build sessions and train the model
with tensorFlow.Session() as sess:
sess.run(tensorFlow.initialize_all_variables())
for epoch in range(epochs):
epochLoss = 0
i = 0
for temp in range(int(len(data) / batchSize)):
ex, ey = nextBatch(batchSize, i) # takes 500 examples
i += 1
# TO-DO : fix bug here
temp, cos = sess.run((optimizer, cost)) # start session to optimize the cost function
epochLoss += cos
print("Epoch", epoch, "completed out of", epochs, "loss:", epochLoss)
correct = tensorFlow.equal(tensorFlow.argmax(prediction,1), tensorFlow.argmax(y, 1))
accuracy = tensorFlow.reduce_mean(tensorFlow.cast(correct, "float"))
print("Accuracy:", accuracy.eval())
问题是,当我从一个应用程序发送通知并在此处接收时,文本不可见。它仅在此应用程序打开时可见。当我的应用程序未打开时,如何将文本设置为字段?将消息存储到某个类字段并在onResume方法中使用setText()?
答案 0 :(得分:1)
在获取String值后的onReceive方法中将它存储在sharedPreference中,如下所示
public void saveInSharedPreferences(String value){
SharedPreferences sharedpreferences = getSharedPreferences("sharedPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("variable",value);//your String value
editor.commit();
}
你的onReceive方法就像是
public void onReceive(Context context, Intent intent) {
String value = intent.getExtras().getString("hiddenMessage");
saveInSharedPreferences(value);
}
并在您的活动的onCreate方法中
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String value = getValueFromSharedPreference();
if(value != null){
textview.setText(value);
}
}
getValueFromSharedPreference方法
public String getValueFromSharedPreference(){
SharedPreferences sharedpreferences = getSharedPreferences("sharedPref", Context.MODE_PRIVATE);
return sharedpreferences.getString("variable",null);
}
现在,如果您想在应用程序打开时更新Textview 试试这个
public void onReceive(Context context, Intent intent) {
String value = intent.getExtras().getString("hiddenMessage");
saveInSharedPreferences(value);
Intent intent = new Intent("broadcast");
intent.putExtra("variable",value);
context.sendBroadCast(intent);
}
然后在你的Activity的oncreate方法
中registerReceiver(broadcastReceiver, new IntentFilter("broadcast"));
然后在您的活动的类中,在oncreate方法
之外BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String value = intent.getStringExtra("variable");
textview.setText(value);
}
};
或者您甚至可以使用此界面解决方案:https://stackoverflow.com/a/26268569/6799807
答案 1 :(得分:0)
首先在onRecieve方法中保存sql中的细节
private void saveNotification(String msg) {
//notification_sql class to save detail
Notification_sql n=new Notification_sql(getApplicationContext());
Notification_detail notification_detail=new Notification_detail();
//notification detail model class to set and get get detail
notification_detail.setData(msg);
n.adddetail(notification_detail);
}
第二次保存数据库中的详细信息
public String adddetail(Notification_detail dataval){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DATE_OF_ENTRY,dataval.getData());
// Inserting Row
db.insert(TABLE_NAME, null, values);
db.close(); // Closing database connection
return null;
}
使用主要活动中的任务sheduler获取数据
scheduleTaskExecutor= Executors.newScheduledThreadPool(5);
// This schedule a task to run every 10 minutes:
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
// If you need update UI, simply do this:
runOnUiThread(new Runnable() {
public void run() {
//update text view
Notification_sql meter_data=new Notification_sql(MapsActivity.this);
//getting detail from database which is saved just after message delivery
List<Notification_detail> contacts = meter_data.getDetail();
//System.out.println(contacts);
for (Notification_detail cn : contacts) {
String data=cn.getData();
txtdetail.setText(data)
}
}
});
}
}, 0, 10, TimeUnit.SECONDS);